import QtQuick 2.0
import Planner 0.1

import '../js/statics.js' as Statics
import '../js/utils.js' as Utils

Item {
  id: root
  width: Statics.window.width
  height: Statics.window.height
  //color: Statics.pallete.background

  Component {
    id: plan
    Plan {}
  }

  /* signal handlers */
  function addPlanClickedHandler() {
    dialog.clear();
    root.state = "dialog";
  }

  function delClickedHandler(idx) {
    removePlan(idx);
  }

  property int modifyingItemIdx: -1

  function modifyClickedHandler(idx, planInfo) {
    dialog.setValue(planInfo);
    root.state = "dialog";
    modifyingItemIdx = idx;
  }

  function planstateSwippedHandler(idx, planstate) {
    updatePlan(idx, {state: planstate});
  }

  function dialogCanceledHandler() {
    root.state = "";
    root.modifyingItemIdx = -1;
  }

  function dialogCompletedHandler(planInfo) {
    if(root.modifyingItemIdx === -1) // add new plan
      addPlan(planInfo);
    else
      updatePlan(modifyingItemIdx, planInfo);

    modifyingItemIdx = -1;
    root.state = "";
  }

  // helper function to handle plan addition to the model
  function addPlan(p) {
    var info = {
      title: p.title || "Title",
      date: p.date || new Date(),
      description: p.description || "Plan description",
      state: p.state || Plan.NOT_START
    }

    p = plan.createObject(this, info);
    model.add(p);
  }

  // helper function to remove plan in the model
  function removePlan(idx) {
    root.showDetailed = false;
    model.remove(idx);
  }

  function updatePlan(idx, planInfo) {
    model.beginUpdate();
    for(var role in planInfo)
      model.modify(idx, planInfo[role], Utils.map[role]);
    model.endUpdate();
  }

  ToolBar {
    id: toolbar
    width: parent.width
    height: Statics.toolbar.height
    onAddClicked: addPlanClickedHandler()
  }

  ListView {
    id: view
    clip: true
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.top: toolbar.bottom
    anchors.bottom: parent.bottom
    model:model
    delegate: delegate
    section{
      property: "state"
      criteria: ViewSection.FullString
      labelPositioning: ViewSection.InlineLabels
      delegate: labelDelegate
    }

//    displaced: Transition {
//      NumberAnimation { properties: "x,y"; duration: Statics.time.quick; easing.type: Easing.InOutQuad }
//    }
  }

  /* delegates */

  // label delegate
  Component {
    id: labelDelegate
    Rectangle {
      width: view.width
      height: 20
      color: section == Plan.NOT_START ? "#aa3333" :
             section == Plan.PROGRESSING ? "#3333aa" :
             "#33aa33"
      Text {
        anchors.centerIn: parent
        text: section == Plan.NOT_START ? "尚未开始" :
              section == Plan.PROGRESSING ? "进行中" :
              "已完成"
        font.pixelSize: Statics.font_size.normal
        color: Statics.pallete.foreground
      }
    }
  }

  // planviewitem delegate
  property bool showDetailed: false

  Component {
    id: delegate
    PlanViewItem {
      datamodel: model
      isCurrentItem: ListView.isCurrentItem
      width: ListView.view.width
      showDetailed: ListView.isCurrentItem && root.showDetailed ? true : false
      onClicked: { // handle item view state
        if(view.currentIndex == index)
          root.showDetailed = !root.showDetailed
        else
          root.showDetailed = true
        view.currentIndex = index
//        console.log('Clicked')
//        console.log("Show Detailed Global flag: " + root.showDetailed)
//        console.log("ShowDetailed state of current item: " + showDetailed)
      }

      onDelClicked: delClickedHandler(index)
      onEditClicked: modifyClickedHandler(index, {
                                            title: model.title,
                                            date: model.date,
                                            description: model.description,
                                            state: model.state
                                          });
      onPlanstateSwipped: root.planstateSwippedHandler(index, state)
    }
  }

  /* the model */

  PlannerModel {
    id: model
  }

  /* Dialog */
  Rectangle {
    id: layer
    anchors.fill: root
    color: Statics.pallete.layer_color
    opacity: 0
    enabled: false
    MouseArea {// blocks out mouse event under this layer
      enabled: parent.enabled
      anchors.fill: parent
    }
  }

  Dialog {
    id: dialog
    width: parent.width - Statics.dialog.margin_left - Statics.dialog.margin_right
    height: parent.height - Statics.dialog.margin_top - Statics.dialog.margin_bottom
    x: parent.width + Statics.dialog.margin_left
    y: Statics.dialog.margin_top

    color: Statics.pallete.dialog_background

    onCanceld: root.state = ""
    onFinished: root.dialogCompletedHandler(p)
  }

  /* states and transitions */
  states: [
    State {
      name: "dialog"
      PropertyChanges {
        target: layer
        enabled: true
        opacity: 0.4
      }
      PropertyChanges {
        target: dialog
        x: Statics.dialog.margin_left
      }
    }
  ]
  transitions: [
    Transition {
      from: ""; to: "dialog"
      reversible: true
      SequentialAnimation {
        NumberAnimation { target: layer; property: "opacity"; duration: Statics.time.normal; easing.type: Easing.InOutQuad }
        NumberAnimation { target: dialog; property: "x"; duration: Statics.time.normal; easing.type: Easing.InOutQuad }
      }
    }
  ]

  // construct map from role string to enum value
  Component.onCompleted:  {
    Utils.map["title"] = PlannerModel.TITLE;
    Utils.map["date"] = PlannerModel.DATE;
    Utils.map["description"] = PlannerModel.DESCRIPTION;
    Utils.map["state"] = PlannerModel.STATE;
    Utils.map["state_str"] = PlannerModel.STATE_PRINTABLE;
  }
}
